import { Module } from "vuex"
import { IRootState, ILoginState } from "@/types/userType"
import { accountLoginRequest, requestLoginInfo, requestUserMenu } from "@/api/login/login"
import localCach from "@/api/localCach"
import router from "@/router/index"

import loadRoutes from "@/router/loadroutes"

import { mapMenuWithPermission } from "@/utils/map-menus"

const login: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenu: [],
      perimssions: [],
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },

    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },

    changeUserMenu(state, userMenu: []) {
      state.userMenu = userMenu
    },
    changUserPermissions(state, permissions: string[]) {
      state.perimssions = permissions
    },
  },
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      console.log(payload)
      const { id, token } = await accountLoginRequest(payload)
      console.log(id)
      console.log(token)

      //1. 保存token
      commit("changeToken", token)
      // 本地缓存token
      localCach.cachLocal("token", token)

      //2. 请求用户信息
      const userInfo: any = await requestLoginInfo(id)
      commit("changeUserInfo", userInfo)
      // 本地缓存userInfo
      localCach.cachLocal("userInfo", userInfo)

      // 3. 请求用户菜单列表
      const userMenu = await requestUserMenu(userInfo.role.id)
      commit("changeUserMenu", userMenu)
      // 本地缓存
      localCach.cachLocal("userMenu", userMenu)

      // 4.查询权限
      const perimssions = mapMenuWithPermission(userMenu)

      // 持久化权限
      commit("changUserPermissions", perimssions)
      // 本地缓存
      localCach.cachLocal("perimssions", perimssions)

      // 加载动态路由
      const routes = loadRoutes(userMenu)
      routes.forEach((item) => {
        router.addRoute("main", item)
      })

      // 5.跳转页面
      router.push("/main")
    },

    // 从本地取数据,同步到store中
    loadLocalLogin({ commit }) {
      commit("changeToken", localCach.getCach("token") ?? "")
      commit("changeUserInfo", localCach.getCach("userInfo") ?? "")
      commit("changeUserMenu", localCach.getCach("userMenu" ?? ""))
      commit("changUserPermissions", localCach.getCach("perimssions" ?? ""))
      if (localCach.getCach("userMenu" ?? "")) {
        // 获取匹配的路由模块
        const routes = loadRoutes(localCach.getCach("userMenu"))
        routes.forEach((item) => {
          router.addRoute("main", item)
        })
      }
    },
  },
}

export default login
